package org.NooLab.itexx.app.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

import org.NooLab.itexx.app.gui.definition.ITexxWindowGuiIntf;
import org.NooLab.itexx.app.gui.handlers.CliccCounter;
import org.NooLab.itexx.app.gui.handlers.PanelText;
import org.NooLab.itexx.app.gui.handlers.ResultPanelMouseHandling;
import org.NooLab.itexx.app.gui.handlers.ResultPanelPopupMenu;
import org.NooLab.itexx.app.gui.handlers.WindowAppearanceIntf;
import org.NooLab.itexx.app.gui.handlers.WindowToggler;
import org.NooLab.itexx.app.gui.handlers.keys.*;
import org.NooLab.itexx.browser.KeyCodes;


import org.NooLab.utilities.files.DFutils;
import org.NooLab.utilities.logging.PrintLog;

import java.awt.Color;




public class CombiPanel extends BackgroundPanel{// BackgroundPanel{ // BackgroundPanel

	// TransparentButton jButton;
	JButton jButton;
	JPanel jPanelBW ,jPanelBN,jPanelBS,jPanelBE,jPanelCM;
	
	
	PanelText paneltext;
	
	String guidStr ="" ;
	Dimension wrapperPanelDim ;
	int padding = 8;
	
	int clics =0;
	CliccCounter cliccCounter; 
	int lastPanelKey = -1;
	long lastPanelKeyTime = -1L;
	
	TransparentTextPane panelsTextPane, panelsMetaTextBottom ;
	JPanel panelsBottomPanel;
	
	Image imgMouseOut=null, imgMouseIn=null;
	private StackedPanel parentObj;
	private Keyhandlers keyHandlers;
	private ITexxWindowGuiIntf windowGui;
	private WindowAppearanceIntf windowAppearance, resultsDisplayagent,windowState;
	private JFrame frame;
	private int panelIndex;
	private ResultPanelMouseHandling resultPanelMouseHandling;
	private ResultPanelPopupMenu popupMenu;
	
	private CombiPanel combiPanel;
	
	boolean eventWasPopupTrigger;
	
	private PrintLog out ;// = new PrintLog(2,true);
	// ========================================================================
	
	public CombiPanel(StackedPanel stackedPanel , String imageSourcePath) throws IOException {
		
		
		init(stackedPanel);
		// setBackgroundImage(imageSourcePath);
	
		
	}

	public CombiPanel(StackedPanel stackedPanel) throws IOException {
		super();
		init(stackedPanel);
	}
	public CombiPanel(StackedPanel stackedPanel , Image img) throws IOException {
		super();
		imgMouseOut = img;
		init(stackedPanel);
	}
	

	private void init(StackedPanel stackedPanel){	
		// new ImagePanel(new ImageIcon( imageSourcePath ).getImage());
		
		combiPanel = this;
		parentObj = stackedPanel;
		out = parentObj.getWindowGui().getOut();
		
		resultPanelMouseHandling = new ResultPanelMouseHandling(parentObj);
		
		panelIndex = stackedPanel.getPanelProducer().getPanels().size() ;
		keyHandlers = parentObj.getWindowGui().getTexxWindowApp().getAppCommons().getKeyHandlers() ;
		
		guidStr = parentObj.getGuid();
		
		windowGui = parentObj.getWindowGui() ;
		frame = windowGui.getTexxWindowApp().getMainFrame();
		
		wrapperPanelDim = parentObj.getWindowGui().getjPanelScrollWrapFoundStack().getSize() ;
		
		if ((wrapperPanelDim.width<30) || (wrapperPanelDim.height<30)){
			wrapperPanelDim = parentObj.getWindowGui().getjPanelScrollWrapFoundStack().getPreferredSize();
			parentObj.getWindowGui().getjPanelScrollWrapFoundStack().setSize(wrapperPanelDim) ;
		}
		
		cliccCounter = new CliccCounter();
		// 
		definePanel();
		produceBorderPanels();
		
		// the later components are drawn beneath the former ones!
		// produceMTextBottom() ;
		
		produceEHText(); // could be textpane or editorpane
		
		
		setOpaque(true) ;
		setBackground( new Color(0.6f,0.6f,0.6f,0.88f));
		setVisible(true) ;
		validate();
		repaint();
		
		paneltext = new PanelText(this) ;
		paneltext.setContentType("text/html") ;
		
		popupMenu = windowGui.getResultPanelPopupMenu();
		// popupMenu.setPopupMenuForPanel(panelsTextPane);
		// popupMenu.setPopupMenuForPanel( this);
	}

	public void setParent( StackedPanel stackedPanel){	
		parentObj = stackedPanel;
	}

	public PanelText getPanelText() {
		return paneltext;
	}

	public void setPanelText(PanelText pText) {
		// 
		paneltext = pText;
	}

	public void updateText() {
		// 
		String str;
		str = paneltext.getText();
		setText(str);
	}

	private void setText(String str){
		// is it html? if yes, send it to setHtmlText
		// if not , adapt contentType to "text/plain"
		
		if ((panelsTextPane.getContentType().contains("html")) ){

			setHtmlText( str );
			
		}else{
			panelsTextPane.setText(str);
		}
		
	}
	
	public void setTransparency(float transparency) {
		// 
		setBackground( new Color(0.6f,0.6f,0.6f,transparency));
	}

	private String prepareStringAsHtml(String str) {
		// 
		return "";
	}

	protected void setHtmlText(String htmlStr){

		try {
			// replace \n with </br>
			// URL url = new
			// URL("http://www.tactika.com/realhome/contents.html");
			// panelsTextPane.setPage("");// url);
			panelsTextPane.setText( htmlStr) ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		// panelsTextPane.		  
	}
	
	
	  
	private void setBackgroundImage2(String imageSourcePath) throws IOException {
		// 
		// is it a resource? or a file path?
		if (DFutils.fileExists(imageSourcePath)){
			
		}else{

		}
		
		BufferedImage myPicture = ImageIO.read(new File(imageSourcePath));
		JLabel picLabel = new JLabel(new ImageIcon( myPicture )) ;
		add( picLabel );

	}

	private void definePanel() {
		// 
		
		setSize( wrapperPanelDim.width-18, 150);
		setPreferredSize( new Dimension(wrapperPanelDim.width-2*padding, 150));
		
		setMinimumSize(new java.awt.Dimension(150, 80));
		setMaximumSize(new java.awt.Dimension(32767, 150));
		
		
		this.setLocation(padding, padding);
		// setPreferredSize(new java.awt.Dimension(100, padding));
		
		setName("jPanel-"+guidStr);

		BorderLayout jPanelLayout = new BorderLayout();
		setLayout( jPanelLayout );

	}
	// ========================================================================
	
	private void produceMTextBottom(){
		
		Dimension d = new Dimension(200,28);
		/*
		panelsMetaTextBottom = new TransparentTextPane( null, 0.4f, "group : ");

		Font f12 = new Font("Tahoma", 14, 14);
		panelsMetaTextBottom.setText("group : ") ;
		
		
		panelsMetaTextBottom.setSize(d);
		panelsMetaTextBottom.setPreferredSize(d);
		panelsMetaTextBottom.setMinimumSize(d) ;
		
		
		panelsMetaTextBottom.setBackground( new Color(0.3f,0.3f,0.3f,0.3f) );
		
		panelsMetaTextBottom.setForeground(new Color(0.2f,0.2f,0.8f));

		panelsMetaTextBottom.setContentType("text/html") ;
		panelsMetaTextBottom.setOpaque(true) ;
		
		panelsMetaTextBottom.setEditable(false) ;
		panelsMetaTextBottom.validate() ;
		*/
		JLabel jLabelMetaInfo = new JLabel("abc");
		jLabelMetaInfo.setText("abc");
		
		jLabelMetaInfo.setMinimumSize(d);
		jLabelMetaInfo.setPreferredSize(d);
		jLabelMetaInfo.setOpaque(true);
		add(jLabelMetaInfo,BorderLayout.CENTER);
		
		// getParent().
		
		// panelsTextPane.getParent().add(panelsMetaTextBottom,BorderLayout.SOUTH);

	}
	
	// --- events -------------------------------------------------------------
	
	private void produceEHText() {
	
		
		panelsTextPane = new TransparentTextPane( imgMouseOut, 0.7f, "");
		//JTextPane jEditorPane = new JTextPane();
		Font f14 = new Font("Tahoma", 14, 14);
		
		panelsTextPane.setText("") ;
		
		panelsTextPane.setSize( getSize()) ;
		panelsTextPane.setBounds( 10, 10, getSize().width-20, getSize().height-20);
	
		panelsTextPane.setForeground(new Color(0f,0f,0f,0.98f));
		panelsTextPane.setBackground(new Color(0.6f,0.6f,0.6f,0.8f));
		panelsTextPane.setOpaque(true) ;
		
		panelsTextPane.setFont(f14);
		panelsTextPane.setContentType("text/html") ;
		
		
		panelsTextPane.setEditable(false) ;
		panelsTextPane.validate() ;
		panelsTextPane.repaint() ;
		
		add(panelsTextPane,BorderLayout.CENTER);
		
		
		
		panelsTextPane.addMouseListener(new MouseAdapter() {

			
			public void mouseReleased(MouseEvent evt) {
				if (evt.isPopupTrigger()){
					eventWasPopupTrigger = true;
					// panelsTextPaneMouseClicked(evt,panelIndex);
					out.printErr(4, "  - - - - - mouseReleased , eventWasPopupTrigger ");
					windowGui.getResultPanelPopupMenu().show(panelIndex,panelsTextPane,evt);
					
				}else{
					out.printErr(4, "  - - - - - mouseReleased ");
					eventWasPopupTrigger = false;
					panelsTextPaneMouseClicked(evt);
				}
			}
			public void mousePressed(MouseEvent evt) {
				if (evt.isPopupTrigger()){
					eventWasPopupTrigger = true;
					out.printErr(4, "  - - - - - mousePressed , eventWasPopupTrigger ");
					windowGui.getResultPanelPopupMenu().show(panelIndex, panelsTextPane,evt);
				}else{
					out.printErr(4, "  - - - - - mousePressed ");
					eventWasPopupTrigger = false;
				}
			}
			public void mouseClicked(MouseEvent evt) {
				out.printErr(4, "  - - - - - mouseClicked");
				if (evt.isPopupTrigger()){
					// windowGui.getResultPanelPopupMenu().show(panelIndex,panelsTextPane,evt.getX(), evt.getY(),evt);
					eventWasPopupTrigger = true;
					out.printErr(4, "  - - - - - mouseClicked, eventWasPopupTrigger ...");
				}else{
					out.printErr(4, "  - - - - - mouseClicked, normal...");
					// panelsTextPaneMouseClicked(evt);
					eventWasPopupTrigger = false;
				}
			}
			public void mouseExited(MouseEvent evt) {
				panelsTextPaneMouseExited(evt);
			}
			public void mouseEntered(MouseEvent evt) {
				eventWasPopupTrigger = false;
				panelsTextPaneMouseEntered(evt);
			}
			
		});
		
		windowAppearance = windowGui.getTexxWindowApp().getAppCommons().getWindowAppearanceEngine() ;
		resultsDisplayagent = windowGui.getTexxWindowApp().getAppCommons().setResultsDisplayAgent() ;
		windowState = windowGui.getTexxWindowApp().getAppCommons().getWindowStateEngine() ;
		int r;  
		
		if (keyHandlers!=null){
			Keyhandler panelsTextPaneKeys = keyHandlers.create(100+panelIndex); // that's an id
			panelsTextPaneKeys.attachGlobalKeys(panelsTextPane,windowAppearance,resultsDisplayagent );
			// any special keys only for panels define like this...
		
			panelsTextPaneKeys.addAction("up", (KeyActionIntf)(new WindowScroller(windowState,-1,-1) ) ); // 1 = arbitrary parameter, later a param object!! untyped array or the like
		 
			r = keyHandlers.getAppKeyListener().add( panelsTextPane, 1, panelsTextPaneKeys); 
		}
		
		/*
		panelsTextPane.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent evt) {
				panelsTextPaneKeyPressed(evt);
			}
		});
		*/
	
	}

	// ------------------------------------------------------------------------
	private void produceBorderPanels(){
	
	
			jPanelBW = new JPanel();
			jPanelBW.setMaximumSize(new java.awt.Dimension(padding, 32767));
			jPanelBW.setPreferredSize(new java.awt.Dimension(padding, 144));
			jPanelBW.setMinimumSize(new java.awt.Dimension(padding, 80));
			jPanelBW.setOpaque(false);
			jPanelBW.setBackground( new Color(0.4f,0.4f,0.5f,0.6f));
			
			jPanelBN = new JPanel();
			jPanelBN.setPreferredSize(new java.awt.Dimension(309, padding));
			jPanelBN.setMinimumSize(new java.awt.Dimension(100, padding));
			jPanelBN.setMaximumSize(new java.awt.Dimension(32767, padding));
			jPanelBN.setOpaque(false);
			jPanelBN.setBackground( new Color(0.3f,0.3f,0.5f,0.5f));
			
			jPanelBS = new JPanel();
			jPanelBS.setPreferredSize(new java.awt.Dimension(100, padding));
			jPanelBS.setMinimumSize(new java.awt.Dimension(100, padding));
			jPanelBS.setMaximumSize(new java.awt.Dimension(32767, padding));
			jPanelBS.setOpaque(false);
			jPanelBS.setBackground( new Color(0.3f,0.8f,0.3f,0.5f));
			
			/*
			jPanelBS.addMouseListener(new MouseAdapter() {
				public void mouseReleased(MouseEvent evt) {
					out.print(2, "mouse event on border panel detected: pressed and released: \n"+ 
								 "        - "+evt.getComponent() +"\n"+
								 "        - "+evt+"\n");
					if (evt.isPopupTrigger()){
						// panelsTextPaneMouseClicked(evt,panelIndex);
						windowGui.getResultPanelPopupMenu().getPanelPopupMenu().show(evt.getComponent(), evt.getX(), evt.getY());
					}
				}
				public void mousePressed(MouseEvent evt) {
					out.print(2, "mouse event on border panel detected: pressed and released: \n"+ 
								 "        - "+evt.getComponent() +"\n"+
								 "        - "+evt+"\n");
					if (evt.isPopupTrigger()){
						// panelsTextPaneMouseClicked(evt,panelIndex);
						windowGui.getResultPanelPopupMenu().getPanelPopupMenu().show(evt.getComponent(), evt.getX(), evt.getY());
					}
				}

			});
			*/
			jPanelBE = new JPanel();
			jPanelBE.setMinimumSize(new java.awt.Dimension(padding, 80));
			jPanelBE.setPreferredSize(new java.awt.Dimension(padding, 144));
			jPanelBE.setMaximumSize(new java.awt.Dimension(padding, 32767));
			jPanelBE.setOpaque(false);
			jPanelBE.setBackground( new Color(0.5f,0.3f,0.3f,0.5f));
	
			//jPanelCM = new BackgroundPanel(imgMouseOut);
			jPanelCM = new JPanel();
			jPanelCM.setMinimumSize(new java.awt.Dimension( 100, 80));
			jPanelCM.setPreferredSize(new java.awt.Dimension(getWidth()-2*padding, getHeight()-2*padding));
			jPanelCM.setMaximumSize(new java.awt.Dimension(getWidth()-2*padding, getHeight()-2*padding));
			jPanelCM.setSize(new java.awt.Dimension(getWidth()-2*padding, getHeight()-2*padding));
	
			jPanelCM.setOpaque(false);
			jPanelCM.setBackground( new Color(0.8f,0.3f,0.3f,0.5f));
	
			
		this.add(jPanelBW, BorderLayout.WEST);
		this.add(jPanelBN, BorderLayout.NORTH);
		this.add(jPanelBS, BorderLayout.SOUTH);
		this.add(jPanelBE, BorderLayout.EAST);
		this.add(jPanelCM, BorderLayout.CENTER);
	}

	// we need double clicks... -> parentObj.openDocumentRequest() ; 
	private void panelsTextPaneMouseClicked(MouseEvent evt) {
		
		out.printErr(2, "panel mouse click : "+evt.toString());
		
		if ((eventWasPopupTrigger) || (evt.isPopupTrigger())){
			// panelsTextPaneMouseClicked(evt,panelIndex);
			windowGui.getResultPanelPopupMenu().getPanelPopupMenu().show(evt.getComponent(), evt.getX(), evt.getY());
			parentObj.getWindowGui().getOut().printErr(2,"popup showing up... (?)");
			return;
		}
		
		windowGui.getResultPanelPopupMenu().hide();
		
		// note that this panelIndex is a physical index, we have a mapping from content index to physical index
		// also, note that physical panels are not deleted, just added until the scroll pane is "full" = filled 
		// with the desired amount of panels 
		resultPanelMouseHandling.handling(panelIndex, evt);
		
	}
	
	private void panelsTextPaneMouseClicked(MouseEvent evt, int i) {
		
	}

	private void panelsTextPaneMouseExited(MouseEvent evt) {
		parentObj.setActivated(false);
	}

	private void panelsTextPaneMouseEntered(MouseEvent evt) {
		parentObj.setActivated(true);
	}
	
	/*
	private void panelsTextPaneKeyPressed(KeyEvent evt) {
		// 
		parentObj.getWindowGui().getOut().print(2, "key pressed : "+ evt.getKeyCode());
		// [iTexx-Gui] key pressed : 17
		// [iTexx-Gui] key pressed : 87
		//
		
		// 16 = shift, 18 = alt
		// 17 = ctrl
		
		
		if ((lastPanelKey==17) && (lastPanelKeyTime>1000000) && (lastPanelKeyTime-System.currentTimeMillis()<18)){
			
			if (evt.getKeyCode()==87){
				parentObj.getPanelProducer().getAppCommons().toggleAppWindowState();
				lastPanelKey = 0;
				lastPanelKeyTime = -1L;
			}
			if (evt.getKeyCode()==88){
				parentObj.getWindowGui().getTexxWindowApp().close();
			}
			if ((new KeyCodes(evt.getKeyCode(),lastPanelKey)).is("x","ctrl")){
				parentObj.getWindowGui().getTexxWindowApp().close();
			}

		}else{
		
			lastPanelKey = evt.getKeyCode() ;
			lastPanelKeyTime = System.currentTimeMillis();
		}
	}
	 */
	
	/*
	private void produceButton() {
		
		jButton = new TransparentButton("");
		//jButton = new JButton("");
		jButton.setName("jButton-");

		int w = this.getSize().width-2 ;
		int h = this.getSize().height-13 ;
		Dimension d = new Dimension( w,h );
		
		jButton.setPreferredSize( d);
		jButton.setSize(d);
		
		add(jButton, BorderLayout.CENTER);
	}
	*/
	
	public StackedPanel getParentObj() {
		return parentObj;
	}

	
}


